<template>
  <div class="login">
    <Row class="login-model">
      <Col span="24">
        <Card>
          <div style="text-align:center;padding:10px">
            <h2>用户登录</h2>
            <br>
            <Tabs :animated="false" type="line" value="login_pwd">
              <TabPane label="账号密码登陆" name="login_pwd">
                <Form
                  @submit.native.prevent="handleSubmit"
                  ref="formItem"
                  :model="formItem"
                  :rules="FromRule"
                >
                  <FormItem prop="account">
                    <Input
                      :disabled="isValidate"
                      v-model.trim="formItem.account"
                      type="text"
                      placeholder="用户名"
                    >
                      <Icon type="md-person" slot="prepend"/>
                    </Input>
                  </FormItem>
                  <FormItem prop="password">
                    <Input
                      :disabled="isValidate"
                      v-model.trim="formItem.password"
                      type="password"
                      placeholder="密码"
                    >
                      <Icon type="ios-lock" slot="prepend"/>
                    </Input>
                  </FormItem>
                  <FormItem>
                    <!--                         <Checkbox :disabled="isValidate" v-model="formItem.agree">下次登录记住我的身份</Checkbox><br>
                    -->
                    <Button
                      :loading="isSubmit"
                      :disabled="isValidate"
                      html-type="submit"
                      type="primary"
                    >{{isValidate ? '登录验证中':'立即登录'}}</Button>
                  </FormItem>
                </Form>
              </TabPane>
              <TabPane label="手机验证码登陆" name="login_yzm">
                <Form
                  @submit.native.prevent="loginByYzm"
                  ref="formItem_yzm"
                  :model="yzmTable.formItem"
                  :rules="yzmTable.FromRule"
                >
                  <FormItem prop="tel">
                    <Input
                      :disabled="yzmTable.isValidate"
                      v-model.trim="yzmTable.formItem.tel"
                      type="text"
                      placeholder="手机号码"
                    >
                      <Icon type="md-person" slot="prepend"/>
                    </Input>
                  </FormItem>
                  <Row>
                    <Col :span="1" style="width:65%">
                      <FormItem prop="yzm">
                        <Input
                          :disabled="yzmTable.isValidate"
                          v-model.trim="yzmTable.formItem.yzm"
                          placeholder="验证码"
                        >
                          <Icon type="ios-lock" slot="prepend"/>
                        </Input>
                      </FormItem>
                    </Col>
                    <Col :span="1" style="width:35%">
                      <Button
                        v-show="!yzmTable.getYzmFalg"
                        :loading="yzmTable.yzmLoading"
                        type="primary"
                        style="float:right;margin-right:0px !important;width:100%"
                        @click="getYzm()"
                      >获取验证码</Button>
                      <Button
                        v-show="yzmTable.getYzmFalg"
                        style="float:right;margin-right:0px !important;width:100%;cursor:default;"
                      >{{yzmTable.time}}(S)</Button>
                    </Col>
                  </Row>

                  <FormItem>
                    <!--                         <Checkbox :disabled="isValidate" v-model="formItem.agree">下次登录记住我的身份</Checkbox><br>
                    -->
                    <Button
                      :loading="yzmTable.submitLoading"
                      :disabled="yzmTable.isValidate"
                      html-type="submit"
                      type="primary"
                    >{{yzmTable.isValidate ? '登录验证中':'立即登录'}}</Button>
                  </FormItem>
                </Form>
              </TabPane>
            </Tabs>
          </div>
        </Card>
      </Col>
    </Row>
  </div>
</template>
<script>
import md5 from "js-md5";
import { post } from "@/libs/axios-cfg";
import { setRoles } from "@/libs/util";

export default {
  data() {
    const validateYZM = (rule, value, callback) => {
      if(!this.yzmTable.onceGet){
        callback(new Error("请获取验证码"));
      }else  if (!value) {
        callback(new Error("请输入验证码"));
      } else {
        callback();
      }
    };
    return {
      isSubmit: false,
      formItem: {
        account: "",
        password: "",
        validateCode: "",
        agree: true
      },
      yzmTable: {
        formItem: {
          tel: "",
          yzm: "",
          scene: "login"
        },
        getYzmFalg: false,
        onceGet: false,
        isValidate: false,
        FromRule: {
          tel: [
            { required: true, message: "手机不能为空" },
            {
              pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
              message: "手机号码格式不正确"
            }
          ],
          yzm: [{ validator: validateYZM, trigger: "blur" }]
        },
        defaultTime: 60,
        time: null,
        interval: null,
        yzmLoading: false,
        submitLoading: false
      },

      isValidate: false,
      FromRule: {
        account: [{ required: true, message: "账号不能为空" }],
        password: [
          { required: true, message: "请填写密码" },
          { type: "string", min: 6, message: "密码长度不能小于6位" }
        ]
      }
    };
  },
  methods: {
    handleSubmit() {
      if (this.isValidate) {
        return false;
      }
      this.$refs.formItem.validate(valid => {
        if (valid) {
          this.login();
        }
      });
    },
    login() {
      this.isValidate = true;
      try {
        let res = this.post("/login/", {
          tel: this.formItem.account,
          pwd: this.formItem.password
        })
          .then(res => {
            if (this.checkIsSsuccess(res)) {
              this.afterLoginSuccess(res);
            } else {
              this.$Message.error(res.msg);
            }
          })
          .catch(err => {
            console.log(err);
          });
      } catch (error) {
        this.$throw(error);
      }
      // setTimeout(loadings, 0);
      this.isValidate = false;
    },
    afterLoginSuccess(res) {
      sessionStorage.setItem("token", res.data.token);
      sessionStorage.setItem("user", JSON.stringify(res.data));
      sessionStorage.setItem("access", JSON.stringify(res.data.rolesCode));
      setRoles(res.data.rolesCode);
      this.$router.push({ path: "/home" });
    },
    getSeesionId() {
      if (!sessionStorage.getItem("token")) {
        let res = this.post("/login/getSessionId")
          .then(res => {
            if (this.checkIsSsuccess(res)) {
              sessionStorage.setItem("token", res.data);
            } else {
              this.$Message.error(res.msg);
            }
          })
          .catch(err => {
            // console.log(err);
          });
      }
    },
    getYzm() {
      this.$refs.formItem_yzm.validateField("tel", valid => {
        if (!valid) {
          var url = "/login/getYzm";
          this.yzmTable.yzmLoading = true;
          this.post(url, Object.assign({}, this.yzmTable.formItem), {}).then(
            res => {
              this.yzmTable.yzmLoading = false;
              if (this.checkIsSsuccess(res)) {
                var data = res.data;
                sessionStorage.setItem("token", data.token);
                if (data.yzm) {
                  this.yzmTable.formItem.yzm = data.yzm;
                }
                this.yzmTable.getYzmFalg = true;
                this.$Message.success("短信验证码已发出");
                this.yzmTable.time = this.yzmTable.defaultTime;
                this.yzmTable.onceGet = true;
                this.yzmTable.interval = setInterval(() => {
                  this.yzmTable.time--;
                  if (this.yzmTable.time <= 0) {
                    this.yzmTable.getYzmFalg = false;
                    clearInterval(this.yzmTable.interval);
                  }
                }, 1000);
              } else {
             
                this.$Message.error(res.msg);
              }
            }
          );
        }
      });
    },
    loginByYzm() {
      this.$refs.formItem_yzm.validate(valid => {
        if (valid) {
          
          this.yzmTable.submitLoading = true;

          var url = "/login/loginByYzm";
          this.post(url, Object.assign({}, this.yzmTable.formItem), {}).then(
            res => {
              this.yzmTable.submitLoading = false;

              if (this.checkIsSsuccess(res)) {
                this.afterLoginSuccess(res);
              } else {
                   console.log(1);
                if('105' == res['status']||'106' == res['status']){
                  this.yzmTable.onceGet = false;
                }
                this.$Message.error(res.msg);
              }
            }
          );
        }
      });
    }
  },
  created: function() {
    this.getSeesionId();
  },
  beforeDestroy: function() {
    if (this.yzmTable.interval) {
      clearInterval(this.yzmTable.interval);
    }
  }
};
</script>
<style>
body {
  /* background-image: url("../../../assets/images/login-bg.jpg"); */
  /* background:  */
  height: 100%;
}
.login-model {
  width: 340px;
  margin-top: 10%;
  float: right;
  margin-right: 200px;
}
</style>